package com.northpool.operator.pub.service.database;

import com.northpool.operator.annotation.InputParam;
import com.northpool.operator.annotation.InputParams;
import com.northpool.operator.annotation.OperatorInfo;
import com.northpool.operator.common.database.DatabaseUtils;
import com.northpool.operator.param.ParamTool;
import com.northpool.operator.type.TypeEnum;
import com.northpool.operator.utils.StpOperatorHelper;
import com.northpool.resources.datasource.IDataSource;
import com.northpool.resources.datasource.db.DbDataSource;

@OperatorInfo(
        ref = "DropDataset",
        name = "删除数据表"
)
public class DropDataset extends StpOperatorHelper {

    @InputParams({
            @InputParam(ref = "dataSourceId", name = "数据源ID", desc = "数据源ID", type = TypeEnum.DATASOURCE, required = true),
            @InputParam(ref = "tableName", name = "数据表名称", desc = "数据表名称，如: public.table", type = TypeEnum.STRING)
    })
    public DropDataset() {

    }

    @Override
    public void execute(ParamTool params) throws Exception {
        this.log("开始执行数据表删除任务...");
        String dataSourceStr = DatabaseUtils.getDataSourceJson(params.getStr("dataSourceId"));
        String tableName = params.getStr("tableName");

        DbDataSource datasource = null;
        try {
            datasource = (DbDataSource) IDataSource.fromJSON(dataSourceStr);
            if (datasource.hasTable(tableName)) {
                datasource.drop(tableName);
            }
            this.successExit();
        } catch (Exception ex) {
            if (datasource != null) {
                datasource.destroy();
            }
            this.error(ex.getMessage());
            this.failedExit();
        }
    }
}
